package cn.tedu.knows.portal.controller;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
public class SystemController {
    @Value("${knows.resource.path}")
    private File resourcePath;
    @Value("${knows.resource.host}")
    private String resourceHost;
    @Autowired
    private IUserService userService;
    @PostMapping("/register")
    public String register(
            @Validated RegisterVo registerVo,
            BindingResult result){
        log.debug("接收到用户信息：{}",registerVo);
        if (result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            return msg;
        }
            userService.registerStudent(registerVo);
            return "ok";
    }
    @PostMapping("/upload/file")
    //MultipartFile是springmvc框架提供的类型，专门用于接受上传的文件
    //imageFile表单中的文件域name一致
    public String uploadFile(MultipartFile imageFile) throws IOException {
        //根据日期获得path路径
        String path= DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDate.now());
        //path:2021/11/03
        //确定上传路径
        File folder=new File(resourcePath,path);
        //创建文件夹
        folder.mkdirs();
        //随机文件名
        String fileName=imageFile.getOriginalFilename();//原始文件名
        String ext=fileName.substring(fileName.lastIndexOf("."));
        //ext: .jpg
        String name= UUID.randomUUID().toString()+ext;
        //name:[uuid].jpg
        //确定要上传的路径
        File file =new File(folder,name);
        log.debug("上传的路径为：{}",file.getAbsolutePath());
        //执行上传
        imageFile.transferTo(file);
        String url=resourceHost+"/"+path+"/"+name;
        log.debug("生成的url:{}",url);
        return url;
    }

}
